<template>
  <main class="mt40">
    <div  class="flex justify-center text-center">
      <div v-if="!userInfo.openId">
        <k-wx-login
            :key="stateRef"
            appid="wx26e1928e2b3d8260"
            :state="stateRef"
            href="https://study512.oss-cn-shenzhen.aliyuncs.com/weixin-login.css"
            :redirect_uri="platformSystem.domain+'/api/login/weixin/login?systemid='+systemId+'_'+userInfo.id"></k-wx-login>
        <p class="text-center">手机微信扫一扫上面二维码，绑定微信</p>
      </div>
      <div v-else style="padding-top: 100px;">
        <h1 class="fz28 green fb">当前账号已绑定微信</h1>
        <div class="mt20 fz1 fb">后续登录可以使用微信扫一扫快捷登录</div>
      </div>
    </div>

  </main>
</template>
<script setup>
import {getSystemId,defaultDomain} from "@/config/common.js"
const platformSystem =  ref({domain:defaultDomain})
const systemId = ref(getSystemId)
const stateRef = ref(new Date().getTime())
const userStore = useStore.userState()
const persionnum = ref(1800)
var logintimer = null
var periodtimer = null
var endtimer = null
const userInfo = ref({})
// 监听支付轮询回调的方法
const handleListenerWXLoginCallback = async ()=>{
  useLoading().start()
  const resp = await useWexinLoginCallbackApi(stateRef.value,userInfo.value.id)
  if(logintimer)clearInterval(logintimer)
  // 2：获取登录路由参数，是否存在from.如果存在登录以后就跳转到from指定的地址
  // 写入token到cookie中
  useCache("TOKEN").setCache(resp.data.uuid)
  // 把用户信息存放于pinia状态管理
  const userStore = useStore.userState()
  userStore.setLoginUserInfo({...resp.data})
  // 放入到缓存中
  useLoading().finish()
  useMessage().success("绑定成功!")
  handleLoadUserInfo()
}

// 轮询过期二维码刷新的问题
const handleListenerPeriod = ()=>{
  persionnum.value --
  if(persionnum.value<=0) {
    persionnum.value = 1800
    handleChangeState()
  }
}


// 加载用户信息
const handleLoadUserInfo = async () => {
  const resp = await useLoadUserGetApi()
  if(resp && resp.data) {
    userInfo.value = resp.data
    userStore.uuid = resp.data.uuid
    userStore.openId = resp.data.openId
    userStore.username = resp.data.username
    userStore.nickname = resp.data.nickname
    userStore.avatar = resp.data.avatar
    userStore.role = resp.data.role
    userStore.authorFlag = resp.data.authorFlag
    userStore.teacherFlag = resp.data.teacherFlag
    if (!resp.data.openId){
      if(logintimer)clearInterval(logintimer)
      if(periodtimer)clearInterval(periodtimer)
      periodtimer = setInterval(handleListenerPeriod,1000)
      logintimer = setInterval(handleListenerWXLoginCallback,3000)
      endtimer = setTimeout(()=>{
        useMessage().info("请重新刷新二维码，进行登录操作!")
        if(logintimer)clearInterval(logintimer)
        if(periodtimer)clearInterval(periodtimer)
        if(endtimer)clearTimeout(endtimer)
      },1000 * 60)
    }
  }
}

onMounted(()=>{
   handleLoadUserInfo()
})

onUnmounted(()=>{
  if(logintimer)clearInterval(logintimer)
  if(periodtimer)clearInterval(periodtimer)
  if(endtimer)clearTimeout(endtimer)
  // 放入到缓存中
  useLoading().finish()
})

</script>
